<?php

namespace haibao\erp\business\user;

use haibao\erp\business\BusinessException;
use \haibao\erp\model\filter\user\User as UserFilter;

class User extends \haibao\erp\business\Base{
	
	const USER_MAX_FROZEN_TIME = 2;

	public static function login($userName,$password,&$needCode,$code = ''){
		if (!$userName){
			throw new BusinessException('用户名不能为空',self::DATA_EMPTY_NAME);
		}
		if (!$password){
			throw new BusinessException('密码不能为空',self::DATA_EMPTY_PASSWORD);
		}
		
		$data = new \haibao\erp\data\user\User();
		$model = $data->getUserByName($userName);
		if(!$model){
	 		$model = $data->getUserByEmail($userName,false);
			if (!$model){
				$model = $data->getUserByMobile($userName,false);
				if(!$model){
					throw new BusinessException('用户不存在',self::DATA_ERROR_NAME);
				}
			}
		}
		
		if ($needCode){
		    self::checkCaptcha($code);
		}
		
		$userCache = new \haibao\erp\cache\User();
		$time = $userCache->getkUserFrozenTime($userName);
		if($time){
		    if($time >= self::USER_MAX_FROZEN_TIME) {
		        $needCode = 1;
		    }
		}else{
		    $time = 0;
		}
		
		if ($model->Password != md5($password)){
		    $userCache->setUserFrozenTime($userName,$time+1);
		    throw new BusinessException('密码不正确',self::DATA_ERROR_PASSWORD);
		}
		if ($model->Status == \haibao\erp\model\data\user\User::STATUS_DIMISSION ||
		    $model->Status == \haibao\erp\model\data\user\User::STATUS_FROZEN){
		    throw new BusinessException('登录失败',self::DATA_ERROR);
		}
		
		// TODO : 获取当前登陆用户的下属用户Id
		$historyData = array(
		    'userName' => $userName,
		    'password' => $model->Password,
		    'IP' => self::getIPaddress()
		);
		self::saveOperateHistory(\haibao\erp\business\Base::FUNC_CODE_USER_LOGIN, $historyData,$model->Id);
		$userCache->delUserFrozen($userName);
		return $model;
	}
	
	public static function getIPaddress(){
	    $ip='';
	    if (isset($_SERVER)){
	        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
	            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
	            $ip = $_SERVER["HTTP_CLIENT_IP"];
	        } else {
	            $ip = $_SERVER["REMOTE_ADDR"];
	        }
	    } else {
	        if (getenv("HTTP_X_FORWARDED_FOR")){
	            $ip = getenv("HTTP_X_FORWARDED_FOR");
	        } else if (getenv("HTTP_CLIENT_IP")) {
	            $ip = getenv("HTTP_CLIENT_IP");
	        } else {
	            $ip = getenv("REMOTE_ADDR");
	        }
	    }
	    return $ip;
	}
	
	/**
	 * 检查用户是否有下属用户
	 * @param :int $userId 用户Id
	 * @return:boolean
	 */
	public static function checkHasSubUser($userId){
	
		if (!$userId){
			throw new BusinessException('用户ID不能为空',self::DATA_EMPTY_ID);
		}
		$userNames = array();
		$data = new \haibao\erp\data\user\User();
		$subUserIds = $data->getLowerUserById($userId);
		if($subUserIds){
			$userNames = $data->getUserNameByIds($subUserIds);
			unset($userNames[$userId]);
		}
		return $userNames;
	}
	
	/**
	 * @param \haibao\erp\data\filter\User $filter
	 */
	public static function getAll($filter){
	    $data = new \haibao\erp\data\user\User();
	
	    return $data->getAll($filter);
	}
	/**
	 * 获取用户是否有操作权限(包括上下级和同级的权限)
	 * @param : Int $userId 用户Id
	 * @return : boolean
	 */
	public static function getIsCurrentPermissions($userId){
	
	    $lowflag = $sameFlag = false;
	    $userModel = self::getCurrentUser();
	    if($userModel->Permission == \haibao\erp\model\data\user\User::PERMISSION_ADMIN){
	        $lowflag = $sameFlag = true;
	        	
	    }else{
	        if(in_array($userId, $userModel->LowerUser)){
	            $lowflag = true;
	        }
	        if(in_array($userId,$userModel->SameUser)){
	            $sameFlag = true;
	        }
	    }
	    return array($lowflag,$sameFlag);
	}
	
	public static function getUserById($userId){
	    if (!$userId){
	        throw new BusinessException('用户ID不能为空',self::DATA_EMPTY_ID);
	    }
	
	    $data = new \haibao\erp\data\user\User();
	    $model = $data->getUserById($userId);
	    if (!$model){
	        throw new BusinessException('用户不存在',self::DATA_ERROR_NAME);
	    }
	
	    return $model;
	}
	
	
	/**
	 * 设置用户组用户
	 * @param unknown_type $groupId
	 * @param unknown_type $userIds
	 */
	public static function setGroupUser($groupId,$userIds){
		if(empty($groupId)){
			throw new BusinessException('用户所属组不能为空',self::DATA_EMPTY_USER_GROUP);
		}
		$data = new \haibao\erp\data\user\User();
		$data->setGroupUser($groupId, $userIds);
		self::saveOperateHistory(self::FUNC_CODE_USER_ADD, array('GroupId'=>$groupId,'UserIds'=>$userIds));
	}
	
	/**
	 * 添加用户
	 * @param \haibao\erp\model\data\user\User $model
	 */
	public static function addUser($model){
	    self::checkOperation(self::FUNC_CODE_USER_ADD);
	    $data = new \haibao\erp\data\user\User();
	    /* if (!$model->UserName){
	     throw new BusinessException('登录名不能为空',self::DATA_EMPTY_NAME);
	    } */
	    if (!$model->RealName){
	        throw new BusinessException('姓名不能为空',self::DATA_EMPTY_REAL_NAME);
	    }
	    if (!$model->JobNum){
	        throw new BusinessException('工号不能为空',self::DATA_EMPTY);
	    }
	    if (!$model->Email){
	        throw new BusinessException('办公邮箱不能为空',self::DATA_EMPTY_NAME);
	    }
	    /* if (!$model->Groups){
	     throw new BusinessException('用户所属组不能为空',self::DATA_EMPTY_USER_GROUP);
	     } */
	    if (!$model->JobType){
	        $leader = $data->getOneById($model->LeaderId);
	        $model->JobType = $leader->JobType ? $leader->JobType: \haibao\erp\model\data\user\User::JOB_TYPE_OTHER;
	    }
	    if ($data->getUserByName($model->UserName)){
	        throw new BusinessException('用户名称已存在',self::DATA_ERROR_NAME_EXIST);
	    }
	    if ($data->getUserByEmail($model->Email)){
	        throw new BusinessException('办公邮箱已存在',self::DATA_ERROR_EMAIL_EXIST);
	    }
	    if ($model->Mobile && $data->getUserByMobile($model->Mobile)){
	        throw new BusinessException('手机号已存在',self::DATA_ERROR_EMAIL_EXIST);
	    }
	
	    $model->Password = md5(111111);
	    $model->CreateTime = new \DateTime();
	    $model->Status = \haibao\erp\model\data\user\User::STATUS_FORCE_CHANGE_PASSWORD;
	    $model->CreateBy = self::getCurrentUser()->Id;
	
	    $data->add($model);
	    
	    self::saveOperateHistory(self::FUNC_CODE_USER_ADD, $model->toArray(true,true));
	}
	
	/**
	 * 修改用户
	 * @param int $id
	 * @param array $arrSet
	 */
	public static function editUser($id,$arrSet){
	    self::checkOperation(self::FUNC_CODE_USER_EDIT);
	
	    $data = new \haibao\erp\data\user\User();
	    if (isset($arrSet[UserFilter::CONDITION_FIELD_NAME_EMAIL]) && empty($arrSet[UserFilter::CONDITION_FIELD_NAME_EMAIL])){
	        throw new BusinessException('办公邮箱不能为空',self::DATA_EMPTY_NAME);
	    }
	    /* if (isset($arrSet[UserFilter::CONDITION_FIELD_NAME_GROUPS]) && empty( $arrSet[UserFilter::CONDITION_FIELD_NAME_GROUPS])){
	     throw new BusinessException('用户所属组不能为空',self::DATA_EMPTY_USER_GROUP);
	     } */
	    if (isset($arrSet[UserFilter::CONDITION_FIELD_NAME_JOB_TYPE]) && $arrSet[UserFilter::CONDITION_FIELD_NAME_JOB_TYPE] == 0){
	        $leader = $data->getOneById($arrSet[UserFilter::CONDITION_FIELD_NAME_LEADER_ID]);
	        $arrSet[UserFilter::CONDITION_FIELD_NAME_JOB_TYPE] = $leader->JobType && $leader->JobType != 0 ? $leader->JobType : \haibao\erp\model\data\user\User::JOB_TYPE_OTHER;
	    }
	    if ( ($user = $data->getUserByEmail($arrSet[UserFilter::CONDITION_FIELD_NAME_EMAIL])) && $user->Id != $id){
	        throw new BusinessException('办公邮箱已存在',self::DATA_ERROR_EMAIL_EXIST);
	    }
	    if(isset($arrSet[UserFilter::CONDITION_FIELD_NAME_USER_NAME])){
	        unset($arrSet[UserFilter::CONDITION_FIELD_NAME_USER_NAME]);
	    }
	    if(isset($arrSet[UserFilter::CONDITION_FIELD_NAME_REAL_NAME])){
	        unset($arrSet[UserFilter::CONDITION_FIELD_NAME_REAL_NAME]);
	    }
	
	    if(!isset($arrSet[\haibao\erp\model\filter\user\User::CONDITION_FIELD_NAME_GROUPS])){
	        $data->removeUserGroups($id);
	    }
	    $data->updateById($id, $arrSet);
	
	    $arrSet['Id'] = $id;
	    self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, $arrSet);
	}
	
	public static function resetPassword($userId){
	    self::checkOperation(self::FUNC_CODE_USER_EDIT);
	
	    if (!$userId){
	        $userId = self::getCurrentUser()->Id;
	    }
	
	    $data = new \haibao\erp\data\user\User();
	    $user = $data->getUserById($userId);
	    $password = md5(111111);
	    $data->updateById($userId, array('Password'=>$password,'Status'=>\haibao\erp\model\data\user\User::STATUS_FORCE_CHANGE_PASSWORD));
	
	    self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, array('Id'=>$userId,'Passwrod'=>$password));
	}
	
	/**
	 * 设置用户状态
	 * @param int $status
	 * @param string $userId
	 */
	public static function setStatus($status,$userId = null){
		self::checkOperation(self::FUNC_CODE_USER_EDIT);
	
		if (!$userId){
			$userId = self::getCurrentUser()->Id;
		}
	
		$data = new \haibao\erp\data\user\User();
		$data->updateStatus($userId, $status);
	
		self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, array('Id'=>$userId,'Status'=>$status));
	}
}
